﻿

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Drawing.Imaging;
using System.Drawing;
using System.Windows.Interop;
using WindowsInput;
using Microsoft.Win32;
using System.Diagnostics;
using HidDevice;
using TTIServer.TTISettings.Pages;
using System.Runtime.InteropServices;
using WCintiqHID;
using Fluent;
using TTIServer.TTISettings.PenLayouts;
using TTIServer.TTISettings.ExpressKeyLayouts;
using System.Windows.Media.Animation;
using Microsoft.SqlServer.Server;
using System.Data.Linq.Mapping;
using System.Data.Linq;
using TTIServer;
using Treblotto_TabletDefs;
namespace TTIServer.TTISettings
{

	//#define DTZ_1200		0x00c6 //12WX
	//#define DTK_1300		0x0304 //13HD
	//#define PL_550		0x0034 //15X
	//#define PL_800		0x0035 //18SX
	//#define DTZ_2000		0x00c5 //20WSX
	//#define DTZ_2100		0x003f //1st Generation 21UX
	//#define DTK_2100		0x00CC //2nd Generation 21UX
	//#define DTK_2200		0x00FA //22HD
	//#define DTH_2200		0x005B //22HD Touch
	//#define DTK_2400		0x00F6 //24HD
	//#define DTH_2400		0x00F8 //24HD Touch Interface

     
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 

	//public class EMRDevicesEqual : IEqualityComparer<EMRDevice>
	//{

	//	public bool Equals(EMRDevice X, EMRDevice Y)
	//	{

	//		if ((X.PenID.Equals(Y.PenID)) && (X.SerialNum.Equals(Y.SerialNum)))
	//			return true;
	//		else
	//			return false;
	//	}

	//	public int GetHashCode(EMRDevice obj)
	//	{
	//		return obj.ToString().ToLower().GetHashCode();
	//	}

	//}
	


	[Flags()]
	public enum DisplayDeviceStateFlags : int
	{
	    /// <summary>The device is part of the desktop.</summary>
	    AttachedToDesktop = 0x1,
	    MultiDriver = 0x2,
	    /// <summary>The device is part of the desktop.</summary>
	    PrimaryDevice = 0x4,
	    /// <summary>Represents a pseudo device used to mirror application drawing for remoting or other purposes.</summary>
	    MirroringDriver = 0x8,
	    /// <summary>The device is VGA compatible.</summary>
	    VGACompatible = 0x10,
	    /// <summary>The device is removable; it cannot be the primary display.</summary>
	    Removable = 0x20,
	    /// <summary>The device has more display modes than its output devices support.</summary>
	    ModesPruned = 0x8000000,
	    Remote = 0x4000000,
	    Disconnect = 0x2000000
	}


	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
	public struct DISPLAY_DEVICE
	{
		 [MarshalAs(UnmanagedType.U4)]
		 public int cb;
		 [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
		 public string DeviceName;
		 [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
		 public string DeviceString;
		 [MarshalAs(UnmanagedType.U4)]
		 public DisplayDeviceStateFlags StateFlags;
		 [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
		 public string DeviceID;
	    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
		 public string DeviceKey;
	}

	public struct DisplayInformation
	{

		public String DisplayName;
		public String DisplayID;
		public String CintiqName;
		public Rect ScreenBounds;
		
	}

    public partial class MainWindow : RibbonWindow
    {
	    const ushort DTK_2100_PID = 0x00CC;
	    const ushort DTK_2200_PID = 0x00FA;
	    const ushort DTH_2200_PID = 0x005B;
	    const ushort DTK_2400_PID = 0x00F8;
	    const ushort DTH_2400_PID = 0x00F6;

		DTK2400EK my24HDEKs;
		//DTK2100EK PenCanvas2100K;
		
		UserControl TabletEKs;
	    [DllImport("user32.dll")]
		static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);

	    System.Windows.Controls.UserControl myEKFrame;

         	public enum RotationDirection
		   {
			   Left,
			   CCW = Left,
			   Right,
			   CW = Right
		   };


	    public BitmapImage bi;

        //List of the Connected Wacom Devices.
	   List<WCintiqHID.Cintiq> CintiqList = new List<Cintiq>(1);
	   List<clrWIntuosHID.Intuos> IntuosList = new List<clrWIntuosHID.Intuos>(1);

	   WCintiqHID.Cintiq_K CintiqRef;
	   TTIServer.TabletSettings TabletSettingsRef;
	   StylusPointDescription penDescription;

	    //MIDI Devices

	   List<DisplayInformation> myDisplayInformation = new List<DisplayInformation>();

	   private double OldActualHeight=0.0;




		


		private System.Timers.Timer epTimer;
		private WCintiqHID.ScreenFactorClass	mySF = new WCintiqHID.ScreenFactorClass();
		Dialogs.PenRotationReport myPRR;

         private int LastRotationAngle = -1;

         PASWindowClass myPASWindow;
         
	    bool PenRotationEnabled = false;

	    //Momentary DATA LUT?
	    // 804 = Pen Rotation
	    private delegate void ImageUpdateDelegete(String WhichPen);

         Bitmap screenBMP;// = new Bitmap(Screen.PrimaryScreen.Bounds.Height, Screen.PrimaryScreen.Bounds.Width);
         Microsoft.Win32.RegistryKey rkLM = Registry.LocalMachine;
         RegistryKey TPCKey;
         Boolean PanAndScanEnabled;

	    
	    const string Grid1920 = "10,60,110,160,260,460,660,860,1060,1260,1460,1660,1760,1810,1860,1910";
	    const string Grid1600 = "10,60,110,160,240,400,560,720,880,1040,1200,1360,1440,1490,1540,1590";
	    const string Grid1200 = "10,60,110,160,240,400,560,720,880,960,1040,1090,1140,1190";
		const string Grid1280 = "";
		const string Grid1080 = "10,60,110,160,240,400,560,720,880,960,1040,1090,1140,1190";
	    const string Grid800 = "10,60,110,160,240,400,560,720,880,960,1040,1090,1140,1190";

         const string TPCKeyName = "20-\\\\?\\HID#VID_056A&PID_00CC&Col02#7&2dcf6d8d&3&0001#{4d1e55b2-f16f-11cf-88cb-001111000030}";
         const string HPDisplayVal = "\\\\?\\DISPLAY#HWP2690#5&3710aa41&1&UID1048848#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}";
         const string WacomDisplayVal = "\\\\?\\DISPLAY#WAC1022#5&3710aa41&1&UID1048850#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}";
         const string TPCSubkey = "SOFTWARE\\Microsoft\\Wisp\\Pen\\Digimon";
	    //"tabcal displayid=\"\\\\.\\DISPLAY2\" lincal novalidate XGridPts=10,60,110,160,240,400,560,720,880,1040,1200,1360,1440,1490,1540,1590 YGridPts=10,60,110,160,240,400,560,720,880,960,1040,1090,1140,1190";
	    const string TabCalString = "displayid=\"{0}\" lincal novalidate XGridPts={1} YGridPts={2}";

         private static BitmapSource CopyScreen()
         {
              using (var screenBmp = new Bitmap(
                  (int)SystemParameters.VirtualScreenWidth,
                  (int)SystemParameters.VirtualScreenHeight,
                  System.Drawing.Imaging.PixelFormat.Format32bppArgb))
              {
                   using (var bmpGraphics = Graphics.FromImage(screenBmp))
                   {
                        bmpGraphics.CopyFromScreen((int)SystemParameters.VirtualScreenLeft, (int)SystemParameters.VirtualScreenTop, 0, 0, screenBmp.Size);
                        return Imaging.CreateBitmapSourceFromHBitmap(
                            screenBmp.GetHbitmap(),
                            IntPtr.Zero,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());
                   }
              }
         }

         private static BitmapSource CopyPrimaryScreen()
         {
              using (var screenBmp = new Bitmap(
                  (int)SystemParameters.PrimaryScreenWidth,
                  (int)SystemParameters.PrimaryScreenHeight,
                  System.Drawing.Imaging.PixelFormat.Format32bppArgb))
              {
                   using (var bmpGraphics = Graphics.FromImage(screenBmp))
                   {
                        bmpGraphics.CopyFromScreen(0, 0, 0, 0, screenBmp.Size);
                        return Imaging.CreateBitmapSourceFromHBitmap(
                            screenBmp.GetHbitmap(),
                            IntPtr.Zero,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());
                   }
              }
         }



	    public MainWindow( WCintiqHID.Cintiq_K inTabletReference, TabletSettings inTabletSettings)
	    {
		    InitializeComponent();
		    Microsoft.Win32.SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged);

		    CintiqRef = inTabletReference;
		    TabletSettingsRef = inTabletSettings;


		    var device = new DISPLAY_DEVICE();
		    device.cb = Marshal.SizeOf(device);
		    try
		    {
			    for (uint id = 0; EnumDisplayDevices(null, id, ref device, 0); id++)
			    {
				    //Console.WriteLine(String.Format("{0}, {1}, {2}, {3}, {4}, {5}", id, device.DeviceName, device.DeviceString, device.StateFlags, device.DeviceID, device.DeviceKey));
				    //Console.WriteLine();
				    device.cb = Marshal.SizeOf(device);

				    EnumDisplayDevices(device.DeviceName, 0, ref device, 0);

				    //Console.WriteLine(String.Format("{0}, {1}, Device String: {2}, {3}, {4}, {5}", id, device.DeviceName, device.DeviceString, device.StateFlags, device.DeviceID, device.DeviceKey));
				    device.cb = Marshal.SizeOf(device);

				    device.cb = Marshal.SizeOf(device);

				    if (device.DeviceID.Contains("WAC"))
				    {

					    DisplayInformation myDisplayInfo = new DisplayInformation();
					    myDisplayInfo.DisplayID = device.DeviceID;
					    myDisplayInfo.DisplayName = device.DeviceName;
					    myDisplayInfo.CintiqName = CintiqName(device.DeviceID.Substring(0, 15));
					    myDisplayInfo.ScreenBounds = GetDeviceBounds(myDisplayInfo.DisplayName);
					    myDisplayInformation.Add(myDisplayInfo);

				    }

			    }


		    }
		    catch (Exception ex)
		    {
			    Console.WriteLine(String.Format("{0}", ex.ToString()));
		    }
		    //Show and Hide the various cursor/styli that have been prox'd in

		    WindowStartupLocation = WindowStartupLocation.Manual;
		    
	


	    }


        void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
        {
             //System.Windows.Forms.MessageBox.Show(SystemParameters.VirtualScreenHeight.ToString());

        }

	   void UpdateExpressKeyLabels()
	   {
		   //int i = 0, j = 0;

		   //for (i=0; i< EKLabels.GetLength(0); i++)
		   //	for (j=0; j<EKLabels.GetLength(1); j++)
		   //EKLabels[i,j].Content = w21uxEKS.TabletEKs[i,j].ExpressKeyLabel;

	   }

        void InitializeExpressKeys()
        {



        }



	    
	    //get the Object that I will change the visibilty on

	    void HideAndShowCursorsAndTablets()
	   {

		   TabletDeviceCollection AllTablets = Tablet.TabletDevices;

		foreach (TabletDevice td in AllTablets)
		{
			
			Cintiq_ActivateIcon(short.Parse(td.ProductId));

		}

		   List<EMRDevice> CurrentPenList;

		   CurrentPenList = TabletSettingsRef.GetPensProxedIn();

		    foreach (EMRDevice emrd in CurrentPenList)
		    {

			    Cintiq_SetPenImage(emrd.GetDefaultEMRName(emrd.PenTypeInformation.PenID));

		    }

		    

	   }


	    private String CintiqName( string DeviceID )
	    {

		    switch (DeviceID)
		    {
			    case "MONITOR\\WAC1019":
				    return "Cintiq 12WX";
			    case "MONITOR\\WAC1022":
				    return "Cintiq 21UX 2";
			    case "MONITOR\\WAC1027":
				    return "Cintiq 24HD";
			    default:
				    return "";

		    }

	    }

	    private Rect GetDeviceBounds( string DisplayNumber )
	    {
		    System.Windows.Forms.Screen[] myScreen = System.Windows.Forms.Screen.AllScreens;
		    Rect rRect = new Rect();

		    foreach (System.Windows.Forms.Screen ms in myScreen)
		    {

			    if (DisplayNumber.Contains(ms.DeviceName))
			    {
				    rRect.X = (double)ms.Bounds.X;
				    rRect.Y = (double)ms.Bounds.Y;
				    rRect.Width = (double)ms.Bounds.Width;
				    rRect.Height = (double)ms.Bounds.Height;
				    return rRect;
			    }

		    }
		    return new Rect(0,0,0,0);

	    }

		private void SetDialogForCintiq( ushort PID )
		{

			switch (TabletSettingsRef.PID)
			{
				case 0xCC:
					ContentCanvas.Children.Clear();
					PenCanvas2100K = new DTK2100EK();
					ContentCanvas.Children.Add(my24HDEKs);

					break;
				case 0xF8:
					ContentCanvas.Children.Clear();
					my24HDEKs = new DTK2400EK();
					ContentCanvas.Children.Add(my24HDEKs);
					this.MinWidth = 1200;
					this.SizeToContent = System.Windows.SizeToContent.Width;
					break;
			}

		}

        private void wndCintiqSettings_Loaded(object sender, RoutedEventArgs e)
        {

		   penDescription = new StylusPointDescription(new StylusPointPropertyInfo[] {

					    new StylusPointPropertyInfo(StylusPointProperties.X),
					    new StylusPointPropertyInfo(StylusPointProperties.Y),
					    new StylusPointPropertyInfo(StylusPointProperties.NormalPressure),
					    new StylusPointPropertyInfo(StylusPointProperties.Z),
					    new StylusPointPropertyInfo(StylusPointProperties.XTiltOrientation),
					    new StylusPointPropertyInfo(StylusPointProperties.YTiltOrientation),
					    new StylusPointPropertyInfo(StylusPointProperties.BarrelButton)

			});

		   TabletSettingsRef.PID = CintiqRef.GetPID();



		   //this.Left = ((myDisplayInformation[0].ScreenBounds.Width - this.ActualWidth) / 2);
		   //this.Left += myDisplayInformation[0].ScreenBounds.X;
		   //this.Top = ((myDisplayInformation[0].ScreenBounds.Height - this.ActualHeight) / 2);
		   //this.Top += myDisplayInformation[0].ScreenBounds.Y;

		   


		   ImgImage.BeginInit();
		   ImgImage.Source = CopyScreen();
		   ImgImage.EndInit();
		   BitmapImage myBS;

			//This has to be the LAMEST way of checking for PAN and SCAN.
			//Seriously.
			PanAndScanEnabled = SystemParameters.VirtualScreenHeight < 2800 ? true : false;
			if (PanAndScanEnabled)
			{
				PASButton.Header = "Disable Pan And Scan";
				button.Visibility = Visibility.Visible;
			}
			else
			{
				PASButton.Header = "Enable Pan And Scan";
				button.Visibility = Visibility.Collapsed;
			}

		   //System.Drawing.Rectangle myRect;
		   //myRect = System.Windows.Forms.Screen.GetBounds(new System.Drawing.Point(100, 100));

		   //mySF.CintiqXLoc = 0;
		   //mySF.CintiqYLoc = 0;

		   //mySF.CurrentScreenHeight = (short)myRect.Height;
		   //mySF.CurrentScreenWidth = (short)myRect.Width;

		   //mySF.Enable = false;

		   HideAndShowCursorsAndTablets();


		   if (ContentCanvas.Children.Contains(PenCanvas2100K))
		   {

			   Cintiq24HDLensCursor.Visibility = Visibility.Collapsed;
			   Cintiq24HDMouse.Visibility = Visibility.Collapsed;

		   }

		   Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));
		   Arrange(new Rect(0, 0, DesiredSize.Width, DesiredSize.Height));


		   //if (CintiqRef.GetPID() == 0xF8)
		   //	this.MinWidth = 1280;

		   //wc21ux.SendNewDisplayCoords(mySF);
		   myPRR = new TTIServer.TTISettings.Dialogs.PenRotationReport();
		   
		   OldActualHeight = TabletRibbon.ActualHeight;

		   PenCanvas2100K.InitializeEKButtons(TabletSettingsRef);

		   this.PenCanvas2100K.EKOutAnimation();

        }


	    public void NewPenProxedIn( String PenName )
	   {

		   this.Dispatcher.BeginInvoke(new ImageUpdateDelegete(Cintiq_SetPenImage), new object[] { PenName });

	   }

	   void Cintiq_SetPenImage(String WhichImage)
	   {
		   BitmapImage inBI;
		   //Needs to switch to active tablet
		   switch (WhichImage) //Need to Get the 3 other Characters XXX802 to really know Pen Type
		   {
			   case "GripPen":
				   CintiqGripPen.Visibility = System.Windows.Visibility.Visible;
				   break;
			   case "InkPen":
				   CintiqInkPen.Visibility = System.Windows.Visibility.Visible;
				   break;
			   case "ArtPen":
				   CintiqArtPen.Visibility = System.Windows.Visibility.Visible;
				   break;
			   case "AirbrushPen": //Airbrush
				   CintiqAirbrushPen.Visibility = System.Windows.Visibility.Visible;
				   break;
			   case "ClassicPen":
				   CintiqClassicPen.Visibility = Visibility.Visible;
				   break;
			   case "LensCursor":
				   Cintiq24HDLensCursor.Visibility = Visibility.Visible;
				   break;
				case "Mouse":
					Cintiq24HDMouse.Visibility = Visibility.Visible;
					break;
			   default:
				   break;
		   }
	   }

	    void Cintiq_ActivateIcon(short ProductID)
	   {

		    switch (ProductID)
		    {
			    case 0xCC:
				    DTK2100.Visibility = Visibility.Visible;
				    CurrentCintiq.Header = DTK2100.Header;
				    CurrentCintiq.LargeIcon = DTK2100.LargeIcon;
				    CintiqExpressPad.Visibility = Visibility.Visible;
				    CintiqExpressRing.Visibility = Visibility.Collapsed;
				    break;
			    case 0xF8:
					DTK2400.Visibility = Visibility.Visible;
					CurrentCintiq.Header = DTK2400.Header;
					CurrentCintiq.LargeIcon = DTK2400.LargeIcon;
					CintiqExpressPad.Visibility = Visibility.Collapsed;
					CintiqExpressRing.Visibility = Visibility.Visible;
					break;
		    }

	   }


	   void SetPenImage(String WhichImage)
	   {
		   BitmapImage inBI;

		   switch (WhichImage) //Need to Get the 3 other Characters XXX802 to really know Pen Type
		   {
			   case "802":
			   case "80C":
				   //inBI = new BitmapImage(new Uri("Resources/LargeGripPenCustom.png", UriKind.RelativeOrAbsolute));
				   IntuosGripPen.Visibility = System.Windows.Visibility.Visible;
				   break;
			   case "804":
			   case "80A":
				   //inBI = new BitmapImage(new Uri("Resources/LargeArtPen.png", UriKind.RelativeOrAbsolute));
				   IntuosArtPen.Visibility = System.Windows.Visibility.Visible;
				   break;
			   case "806":
				   IntuosMouse.Visibility = Visibility.Visible;
				   break;
			   case "006":
				   IntuosLensCursor.Visibility = Visibility.Visible;
				   break;
			   case "902": //Airbrush
				   break;
			   default:
				   //inBI = new BitmapImage(new Uri("Resources/GripPenPro.png"));
				   break;
		   }



		   //PenImage.BeginInit();
		   //PenImage.Source = inBI;
		   //PenImage.EndInit();
	   }



        void ChangePASWindow()
        {
        }

        private void Grid_Unloaded(object sender, RoutedEventArgs e)
        {
             
        }

        private void wndCintiqSettings_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        public void wndCintiqSettings_Closed(object sender, EventArgs e)
        {
			
        }

        private void wndCintiqSettings_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
			e.Cancel = true;
			this.Visibility = System.Windows.Visibility.Hidden;
        }

        private void Ellipse1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
             //LExpressGroup1LED.Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xFF, 0xFF, 0x00));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
             // Open a New Window that lets me edit the coordinates
			// Send the coordinates to the clrWCintiqHID
             //DisplaySettings myW1 = new DisplaySettings(CintiqRef, mySF);
             //myW1.Show();

			if (PenCanvas2100K.PenCanvas.Children.Count > 0)
				PenCanvas2100K.PenCanvas.Children.Clear();

			if (PenCanvas2100K.ExpressKeysExtended)
				PenCanvas2100K.EKOutAnimation();

			PASLayout myPASLayout = new PASLayout(CintiqRef, mySF);
			PenCanvas2100K.PenCanvas.Children.Add(myPASLayout);


        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

			 //if (TPCKey != null)
			 //{
                  Process myProcess = new Process();

                  try
                  {
                       myProcess.StartInfo.UseShellExecute = false;
                       // You can start any process, HelloWorld is a do-nothing example.
                       myProcess.StartInfo.FileName = "C:\\windows\\system32\\DisplaySwitch.exe";
                       myProcess.StartInfo.CreateNoWindow = true;

                       // This code assumes the process you are starting will terminate itself.  
                       // Given that is is started without a window so you cannot terminate it  
                       // on the desktop, it must terminate itself or you can do it programmatically 
                       // from this application using the Kill method.
                       switch (PanAndScanEnabled)
                       {
                            case true: //PAS is enabled, time to disable...
                                 //Change Tablet PC Screen to Wacom 21UX

                                 //TPCKey.SetValue(TPCKeyName, WacomDisplayVal);
                                 PanAndScanEnabled = false;
                                 PASButton.Content = "Enable Pan and Scan";
                                 myProcess.StartInfo.Arguments = "/extend";
                                 myProcess.Start();
								 PanAndScanEnabled = false;
								 button.Visibility = Visibility.Collapsed;
								 myPASWindow = null;
								 mySF.Enable = false;
								 mySF.CintiqXLoc = 0;
								 mySF.CintiqYLoc = 0;
								 mySF.XFactor = 1;
								 mySF.YFactor = 1;
								 CintiqRef.SendNewDisplayCoords(new ScreenFactorClass());
                                 break;
                            case false: //PAS is disabled, time to enable
                                 /* Change Tablet PC Screen to HP */
                                 //TPCKey.SetValue(TPCKeyName, HPDisplayVal);
                                 myProcess.StartInfo.Arguments = "/clone";
                                 myProcess.Start();
                                 PanAndScanEnabled = true;
								 button.Visibility = Visibility.Visible;
                                 PASButton.Content = "Disable Pan and Scan";
								 myPASWindow = new PASWindowClass(CintiqRef);
								 
                                 break;
                       }
                  }

                  catch (Exception t)
                  {
                       Console.WriteLine(t.Message);
                  }
			 //}
			 //else
			 //	 System.Windows.Forms.MessageBox.Show("Could not Open TPC Key!");


        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
		
		   myPRR.Show();

        }

	   private void Ribbon_SelectionChanged(object sender, SelectionChangedEventArgs e)
	   {

	   }

	   private void Ribbon_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
	   {

	   }

	   private void Ribbon_CintiqExpressKeys_Click(object sender, RoutedEventArgs e)
	   {

            

		   


	   }

	   private void Ribbon_CintiqExpressTouchStrips_Click(object sender, RoutedEventArgs e)
	   {


	   }

	   private void CintiqGripPen_Click(object sender, RoutedEventArgs e)
	   {



		
	   }
	   private void CintiqArtPen_Click(object sender, RoutedEventArgs e)
	   {

		   //if (ContentCanvas.Children.Count > 0)
		   //	ContentCanvas.Children.Clear();

		   //myEKFrame = new ExpressKeyLayouts.DTK2100EK();

		   //DTK2100EK myTempFrame = (DTK2100EK)myEKFrame;

		   //myTempFrame.PenCanvas.Content = (new PenLayouts.PenLayout("804"));

		   //ContentCanvas.Children.Add(myEKFrame);
	   }


	  private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
	  {

		  return IntPtr.Zero;
	  }

	    public enum EMRConstants
	    {
			GPButton = 0,
			APButton, 
			CPButton,
			IPButton,
			ABPButton,
			EKButton,
			EPButton,
			TPButton,
		    TRButton,
			MCButton,
			LCButton,

	    }

	    EMRConstants StringToEMRConstant ( string NickName )
	    {
		    EMRConstants senderVal = EMRConstants.GPButton;

		    switch (NickName)
		    {

			    case "Grip Pen":
				    senderVal = EMRConstants.GPButton;
				    break;
			    case "Art Pen":
				    senderVal = EMRConstants.APButton;
				    break;
			    case "Airbrush Pen":
				    senderVal = EMRConstants.ABPButton;
				    break;
			    case "Classic Pen":
				    senderVal = EMRConstants.CPButton;
				    break;
			    case "Ink Pen":
				    senderVal = EMRConstants.IPButton;
				    break;

		    }

		    return senderVal;
	    }


		private void Uncheck_All_Other_Tools(EMRConstants sender)
		{


			if (!(sender == EMRConstants.GPButton))
				CintiqGripPen.IsChecked = false;

			if (!(sender == EMRConstants.APButton))
				CintiqArtPen.IsChecked = false;

			if (!(sender == EMRConstants.ABPButton))
				CintiqAirbrushPen.IsChecked = false;

			if (!(sender == EMRConstants.IPButton))
				CintiqInkPen.IsChecked = false;

			if (!(sender == EMRConstants.CPButton))
				CintiqClassicPen.IsChecked = false;

			if (!(sender == EMRConstants.EKButton))
				CintiqExpressKeys.IsChecked = false;

			if (!(sender == EMRConstants.EPButton))
				CintiqExpressPad.IsChecked = false;

			if (!(sender == EMRConstants.TRButton))
				CintiqExpressRing.IsChecked = false;

			if (!(sender == EMRConstants.MCButton))
				CintiqExpressRing.IsChecked = false;

			if (!(sender == EMRConstants.LCButton))
				CintiqExpressRing.IsChecked = false;



		}

		private void CintiqExpressKeys_Checked(object sender, System.Windows.RoutedEventArgs e)
		{
			// TODO: Add event handler implementation here.
			if (PenCanvas2100K.PenCanvas.Children.Count > 0)
				PenCanvas2100K.PenCanvas.Children.Clear();

			if (PenCanvas2100K.ExpressKeysExtended == false) ;
				PenCanvas2100K.EKInAnimation();
			Uncheck_All_Other_Tools(EMRConstants.EKButton);
		}

		private void CintiqExpressKeys_Unchecked(object sender, System.Windows.RoutedEventArgs e)
		{
			Console.WriteLine(sender.GetType().ToString());
			PenCanvas2100K.EKOutAnimation();
	  
		}

		private void CintiqGripPen_Unchecked(object sender, RoutedEventArgs e)
		{




		}

		private void CintiqGripPen_Checked(object sender, RoutedEventArgs e)
		{




		if (PenCanvas2100K.PenCanvas.Children.Count > 0)
			PenCanvas2100K.PenCanvas.Children.Clear();

		PenCanvas2100K.PenCanvas.Children.Add((new PenLayouts.PenLayout("802")));

		if (PenCanvas2100K.ExpressKeysExtended)
			PenCanvas2100K.EKOutAnimation();
		 
		Uncheck_All_Other_Tools(EMRConstants.GPButton);

           
		}

		private void Pen_Unchecked(object sender, RoutedEventArgs e)
		{

			//Pen Fade Out is all I need

		}

		private void Pen_Checked(object sender, RoutedEventArgs e)
		{

			string PenID = "";

			if (sender.GetType()==typeof(Fluent.ToggleButton))
			{
				Fluent.ToggleButton myToggleButton = (Fluent.ToggleButton)sender;
				PenID = (string)myToggleButton.Header;
			}


	
			Uncheck_All_Other_Tools(StringToEMRConstant(PenID));


			PenCanvas2100K.changePen((new PenLayouts.PenLayout(PenID)));
			

			//PenCanvas2100K.PenCanvas.Children.Add();

			if (PenCanvas2100K.ExpressKeysExtended)
			{
				PenCanvas2100K.EKOutAnimation();
				CintiqExpressKeys.IsChecked = false;
			}

			


		}

		private void CintiqArtPen_Unchecked(object sender, RoutedEventArgs e)
		{

			
			PenCanvas2100K.PenCanvas.Children.Clear();

		}

		private void CintiqArtPen_Checked(object sender, RoutedEventArgs e)
		{
			if (PenCanvas2100K.PenCanvas.Children.Count > 0)
				PenCanvas2100K.PenCanvas.Children.Clear();

			DTK2100EK myTempFrame = (DTK2100EK)myEKFrame;

			PenCanvas2100K.PenCanvas.Children.Add((new PenLayouts.PenLayout("804")));
			PenCanvas2100K.EKOutAnimation();

		  


		}

		private void CintiqInkPen_Unchecked(object sender, RoutedEventArgs e)
		{

			PenCanvas2100K.EKInAnimation();
			PenCanvas2100K.PenCanvas.Children.Clear();

		}

		private void CintiqInkPen_Checked(object sender, RoutedEventArgs e)
		{
			if (PenCanvas2100K.PenCanvas.Children.Count > 0)
				PenCanvas2100K.PenCanvas.Children.Clear();

			DTK2100EK myTempFrame = (DTK2100EK)myEKFrame;

			PenCanvas2100K.PenCanvas.Children.Add((new PenLayouts.PenLayout("120802")));
			PenCanvas2100K.EKOutAnimation();

		}



		private void TabletRibbon_IsMinimizedChanged(object sender, DependencyPropertyChangedEventArgs e)
		{
			if (OldActualHeight > TabletRibbon.ActualHeight)
				ContentCanvas.Margin = new Thickness(0, OldActualHeight, 32, 0);
			else
				ContentCanvas.Margin = new Thickness(0, TabletRibbon.ActualHeight, 32, 0);

			OldActualHeight = TabletRibbon.ActualHeight;
		}

		private void RibbonWindow_StylusDown(object sender, StylusDownEventArgs e)
		{

			StylusPointDescription wndSPDesc= e.GetStylusPoints(this).Description;
			StylusPointDescription commonDisc = StylusPointDescription.GetCommonDescription(wndSPDesc, penDescription);

			StylusDevice myStylus = e.StylusDevice;
			StylusPointCollection points = myStylus.GetStylusPoints(this, commonDisc);

			Byte MidiNote;
			StylusPointCollection myCollection = e.GetStylusPoints(this, commonDisc);
			int xt, yt;

			xt = points[0].GetPropertyValue(StylusPointProperties.XTiltOrientation);
			yt = points[0].GetPropertyValue(StylusPointProperties.YTiltOrientation);

			Console.WriteLine("XTilt: {0}", xt);
			PlayMidiData(xt);
		  


		}

		private void RibbonWindow_StylusInRange(object sender, StylusEventArgs e)
		{

		}

		private void RibbonWindow_StylusMove(object sender, StylusEventArgs e)
		{
			//Type A, B;

		  

			//if ((PenCanvas2100K.PenCanvas.Children.Count > 0));
			//{
			//	A = PenCanvas2100K.PenCanvas.Children[0].GetType();
			//	B = typeof(PenLayout);


			//	if (A == B)
			//	{
			//		StylusPointCollection myPC = e.GetStylusPoints(this);


			//		PenLayout myPenLayout = (PenLayout)PenCanvas2100K.PenCanvas.Children[0];


			//		for (int i = 0; i < myPC.Count; i++)
			//			if (!e.InAir)
			//			{
			//				if (e.Inverted)
			//					myPenLayout.EraserPrgBar.Value = myPenLayout.EraserPrgBar.Maximum * myPC[i].PressureFactor;
			//				else
			//					myPenLayout.TipPrgBar.Value = myPenLayout.TipPrgBar.Maximum * myPC[i].PressureFactor;
			//			}

			//		if (e.InAir)
			//		{
			//			myPenLayout.EraserPrgBar.Value = 0;
			//			myPenLayout.TipPrgBar.Value = 0;
			//		}
			//	}
			//}
		}

		private void RibbonWindow_StylusLeave(object sender, StylusEventArgs e)
		{


		}

		private void RibbonWindow_StylusUp(object sender, StylusEventArgs e)
		{


			//Type A, B;

			//if (PenCanvas2100K.PenCanvas.Children.Count > 0)
			//{

			//	A = PenCanvas2100K.PenCanvas.Children[0].GetType();
			//	B = typeof(PenLayout);


			//	if (A == B)
			//	{

			//		StylusPointCollection myPC = e.GetStylusPoints(this);
			//		PenLayout myPenLayout = (PenLayout)PenCanvas2100K.PenCanvas.Children[0];

			//		myPenLayout.EraserPrgBar.Value = 0;
			//		myPenLayout.TipPrgBar.Value = 0;
			
			//	}
			//}




		}

	  private void RibbonWindow_StylusInAirMove(object sender, StylusEventArgs e)
	  {

	  }


	  private void DisplayDiag_Clicked(object sender, RoutedEventArgs e)
	  {
		  //PenDigitizer3D myPD3D = new PenDigitizer3D(wc21ux, PenDigitizer3D.DTK2400);

		  //myPD3D.WindowState = WindowState.Maximized;
		  //myPD3D.Topmost = true;
		  //myPD3D.Loaded += delegate
		  //{

		  //	HwndSource source = (HwndSource)PresentationSource.FromDependencyObject(myPD3D);

		  //	source.AddHook(WindowProc);

		  //};


		  //myPD3D.Show();

		  TTIServer.TTISettings.DTK2400Test myTest = new DTK2400Test();
		  myTest.Show();

		
	  }

	  public void Init_Midi()
	  {


		  
	  }

	  public List<String> GetMidiDeviceList()
	  {
		  List<String> MidiList = new List<String>(1);




		  return MidiList;


	  }


	  private void PlayMidiNoteOff(int NoteVal)
	  {

	
		  


	  }

	  private void PlayMidiData(int NoteVal)
	  {


		  



	  }

	  private void CalibrateButton_Click(object sender, RoutedEventArgs e)
	  {
		  Process myProcess = new Process();

		  try
		  {
			  myProcess.StartInfo.UseShellExecute = false;
			  // You can start any process, HelloWorld is a do-nothing example.
			  myProcess.StartInfo.FileName = "C:\\windows\\system32\\tabcal.exe";
			  myProcess.StartInfo.CreateNoWindow = true;
			  myProcess.StartInfo.Arguments = String.Format(TabCalString, myDisplayInformation[0].DisplayName.Substring(0,12), Grid1920, Grid1200);
			  // This code assumes the process you are starting will terminate itself.  
			  // Given that is is started without a window so you cannot terminate it  
			  // on the desktop, it must terminate itself or you can do it programmatically 
			  // from this application using the Kill method.

			  myProcess.Start();
		  }
		  catch (Exception t)
		  {
			  Console.WriteLine(t.Message);
		  }

	  }




    }

     

}
